package com.gds.wiki.cloud.memberCenter.server.security.oauth2.core.authenticator;

import cn.hutool.core.util.StrUtil;
import com.gds.wiki.cloud.framework.common.exception.BizExceptionEnum;
import com.gds.wiki.cloud.framework.common.exception.BusinessException;
import com.gds.wiki.cloud.framework.web.support.HttpKit;
import com.gds.wiki.cloud.oauth2.common.integration.IntegrationAuthentication;
import org.springframework.stereotype.Component;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * 集成验证码认证
 * @author WIKI
 * @date 2018-3-31
 **/
@Component
public class VerificationCodeIntegrationAuthenticator extends UsernamePasswordAuthenticator {

    private final static String VERIFICATION_CODE_AUTH_TYPE = "vc";


    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication){
        String imgCode = integrationAuthentication.getAuthParameter("imgCode");
        if(StrUtil.isEmpty(imgCode)){
            throw new BusinessException(BizExceptionEnum.V_CODE_NULL);
        }
        String sessionImgCode= (String) HttpKit.getRequest().getSession().getAttribute(KAPTCHA_SESSION_KEY);
        if(!imgCode.equals(sessionImgCode)){
              throw new BusinessException(BizExceptionEnum.V_CODE_ERROR);
        }
    }


    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return VERIFICATION_CODE_AUTH_TYPE.equals(integrationAuthentication.getAuthType());
    }
}
